import { addPlZkp, getZkpList, MAGIC_SUCC_CODE } from "../../../api"
export function use() {
  let yqXmData: any[] = []
  const formData = ref({ yqid: '', ph: '', zkspdm: '' }),
    tableData = ref<any[]>([]),
    phList = ref<string[]>([]),
    currentRow = ref<LisZkpItem>(),
    formTable = ref()
  watch(() => ({ ph: formData.value.ph, zkspdm: formData.value.zkspdm }), search)
  watch(() => formData.value.yqid, query)
  function search({ ph, zkspdm }: any) {
    tableData.value = yqXmData.filter(it => (!ph || it.ph == ph) && (!zkspdm || it.zkspdm == zkspdm))
  }
  function query() {
    const param = formData.value, { yqid } = param
    if (yqid) {
      getZkpList(param).then(({ data: { list } }) => {
        yqXmData = list
        phList.value = [...new Set(list.map(it => it.ph || ''))]
        search(formData.value)
      })
    }
  }
  function setFormData(data: any) {
    tableData.value = data
    nextTick(() => {
      if (formTable.value) {
        formTable.value.layout()
      }
    })
  }
  function del() {
    const obj = currentRow.value
    if (obj) {
      const { id } = obj
      setFormData(tableData.value.filter(it => it.id != id))
    } else {
      ElMessage({ type: 'warning', message: '请选择要删除的项目' })
    }
  }
  function add() {
    currentRow.value = { yqid: formData.value.yqid }
  }
  function save() {
    addPlZkp({ data: tableData.value, yqid: formData.value.yqid }).then(({ code, data, message }) => {
      if (code === MAGIC_SUCC_CODE) {
        ElMessage({ type: 'success', message: '新增成功' })
        query()
      } else
        ElMessage({ type: 'warning', message })
    })
  }
  return { formData, tableData, phList, query, currentRow, formTable, del, add, save }
}